import pika
import time


def send_message(host, port, username, password, virtual_host, queue_name, message, num_messages, delay):
    """
    发送指定次数的消息到 RabbitMQ 队列，并在每次发送后等待指定间隔。

    :param host: RabbitMQ 服务器地址
    :param port: RabbitMQ 服务器端口
    :param username: 登录用户名
    :param password: 登录密码
    :param virtual_host: 虚拟主机
    :param queue_name: 队列名
    :param message: 要发送的消息
    :param num_messages: 发送次数
    :param delay: 发送间隔，单位秒
    """
    # 账号密码
    credentials = pika.PlainCredentials(username=username, password=password)

    # 连接
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host=host, port=port, virtual_host=virtual_host, credentials=credentials))

    # 连接通道
    channel = connection.channel()

    # 生产消息
    for i in range(num_messages):
        channel.basic_publish(exchange='',
                              routing_key=queue_name,
                              body=message.encode('UTF-8'))
        print(f'消息 "{message}" 已发送到队列 "{queue_name}".')

        # 如果不是最后一条消息，则等待指定间隔
        if i < num_messages - 1:
            time.sleep(delay)

    # 关闭连接
    connection.close()
    print("所有消息发送完毕。")


import pika

import pika


def consume_queue(consume_queue_name, source_queue_name, host, port, username, password, virtual_host):
    """
    创建一个消费者，声明一个队列，并从指定的源队列中消费消息。

    :param consume_queue_name: 创建的消费队列名称
    :param source_queue_name: 要消费的源队列名称
    :param host: RabbitMQ 服务器的主机名或IP地址
    :param port: RabbitMQ 服务器的端口
    :param username: RabbitMQ 服务器的用户名
    :param password: RabbitMQ 服务器的密码
    :param virtual_host: RabbitMQ 服务器的虚拟主机
    """

    def on_message_received(channel, method, properties, body):
        """
        定义接收消息时的回调函数。
        """
        print(f"Received message: {body.decode()}")
        # 确认消息已经被处理
        channel.basic_ack(delivery_tag=method.delivery_tag)

    # 设置连接参数
    credentials = pika.PlainCredentials(username, password)
    connection_params = pika.ConnectionParameters(
        host=host,
        port=port,
        virtual_host=virtual_host,
        credentials=credentials
    )

    # 连接到 RabbitMQ 服务器
    connection = pika.BlockingConnection(connection_params)
    channel = connection.channel()

    # 声明消费队列
    channel.queue_declare(queue=consume_queue_name, durable=True)
    # 声明源队列（如果需要）
    channel.queue_declare(queue=source_queue_name, durable=True)

    # 绑定消费队列到源队列（如果它们不同）
    # if consume_queue_name != source_queue_name:
    #     channel.queue_bind(exchange='', queue=consume_queue_name, routing_key=source_queue_name)

    # 设置消费者回调函数
    channel.basic_consume(queue=source_queue_name, on_message_callback=on_message_received)

    print(f'Waiting for messages in {source_queue_name}. To exit press CTRL+C')
    # 开始消费消息
    channel.start_consuming()
